package com.ossjk.oa.system.controller;

import java.util.Arrays;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ossjk.core.base.controller.BaseController;
import com.ossjk.core.util.CommonUtil;
import com.ossjk.oa.system.entity.Dictionary;
import com.ossjk.oa.system.service.IDictionaryService;

/**
 * <p>
 * 数据字典 前端控制器
 * </p>
 *
 * @author chair
 * @since 2019-01-14
 */
@RestController
@RequestMapping("/system/dictionary")
public class DictionaryController extends BaseController {
	@Autowired
	private IDictionaryService iDictionaryService;

	@RequiresPermissions("00000020")
	@GetMapping("/list")
	public Object list(String name, String dkey, Page page) {
		Wrapper wrapper = Condition.create().like("name", name).like("dkey", dkey).eq("type", "2");
		page = iDictionaryService.selectPage(page, wrapper);
		return responseSuccess(page);
	}

	@RequiresPermissions("000000200000")
	@PostMapping("/insert")
	public Object insert(Dictionary dictionary) {
		// key不能重复
		// type 类型 1-系统属性、2-自定义属性
		Wrapper wrapper = Condition.create().eq("type", "2").eq("dkey", dictionary.getDkey());
		List<Dictionary> dictionaries = iDictionaryService.selectList(wrapper);
		if (!CommonUtil.isBlank(dictionaries)) {
			return responseFail("key重复了");
		}

		if (iDictionaryService.insert(dictionary)) {
			return responseSuccess();
		} else {
			return responseFail();
		}
	}

	@RequiresPermissions("000000200010")
	@GetMapping("/toUpdate/{id}")
	public Object toUpdate(@PathVariable("id") String id) {
		return responseSuccess(iDictionaryService.selectById(id));
	}

	@RequiresPermissions("000000200010")
	@PutMapping("/update")
	public Object update(Dictionary dictionary) {
		if (iDictionaryService.updateById(dictionary)) {
			return responseSuccess();
		} else {
			return responseFail();
		}

	}

	@RequiresPermissions("000000200015")
	@DeleteMapping("/delete/{id}")
	public Object delete(@PathVariable("id") String[] id) {
		if (iDictionaryService.deleteBatchIds(Arrays.asList(id))) {
			return responseSuccess();
		} else {
			return responseFail();
		}
	}
}
